<template>
  <div class="hl-wrapper">
    <!-- 顶部 -->
    <van-nav-bar title="扫描终端">
      <template #right>
        <van-icon v-if="dataSource.length > 0" name="delete-o" size="18" @click="dataSource = []" />
      </template>
    </van-nav-bar>
    <!-- 内容部分 -->
    <div class="hl-content">
      <van-cell-group v-if="dataSource.length > 0" :border="false">
        <template v-for="(item, index) in dataSource">
          <van-cell :key="index" :title="`${item.name}（${item.type == 1 ? '荤菜' : item.type == 2 ? '素菜' : '未知'}）`" center>
            <template #icon>
              <van-checkbox v-model="item.checked" />
            </template>
            <template #label>
              <span class="hl-price">{{ item.price }}</span>
              <van-tag mark type="success" v-if="item.vitaminA">VA:{{ item.vitaminA }}</van-tag>
              <van-tag mark type="primary" v-if="item.vitaminB">VB:{{ item.vitaminB }}</van-tag>
              <van-tag mark type="warning" v-if="item.vitaminC">VC:{{ item.vitaminC }}</van-tag>
            </template>
            <van-stepper v-model="item.number" :max="item.total" theme="round" button-size="22" disable-input />
          </van-cell>
        </template>
      </van-cell-group>
      <van-empty v-else description="暂无扫描任何商品" />
    </div>
    <!-- 底部 -->
    <van-submit-bar :price="totalPrice" :disabled="totalPrice <= 0" :loading="loading" button-type="info" button-text="提交订单" @submit="onSubmit" />
    <!-- 扫描按钮 -->
    <div class="hl-scan" @click.stop="onscanQRCode"><van-icon name="scan" /></div>
  </div>
</template>
<script>
import { sumBy } from 'lodash'
import { Cell, CellGroup, Checkbox, Stepper, Tag, NavBar, SubmitBar, Empty } from 'vant'
import { mapState } from 'vuex'
import { GetProduct } from '../api/product'
import { SubmitShopOrder } from '../api/store'
// const regexp = {
//   product: /p:\w+$/gi,
//   user: /u:[1-9]+:\w+:/gi
// }
export default {
  name: 'Home',
  components: {
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Checkbox.name]: Checkbox,
    [Stepper.name]: Stepper,
    [Tag.name]: Tag,
    [NavBar.name]: NavBar,
    [SubmitBar.name]: SubmitBar,
    [Empty.name]: Empty
  },
  data() {
    return {
      loading: false,
      dataSource: [
        // { id: 2, name: '第一个菜', type: 1, price: 13.2, total: 2, number: 1, checked: true }
      ]
    }
  },
  computed: {
    ...mapState(['store']),
    //合计金额
    totalPrice: function () {
      return (
        sumBy(
          this.dataSource.filter(f => f.checked),
          o => o.price * o.number
        ) * 100
      )
    }
  },
  methods: {
    //点击扫描
    onscanQRCode() {
      if (this.loading) return
      window.wx.scanQRCode({
        needResult: 1,
        scanType: ['qrCode'],
        success: qrres => {
          const [type, code] = qrres.resultStr.split(':')
          if (type == 'p') {
            const { dataSource } = this
            const index = dataSource.findIndex(x => x.code == code)
            if (index > -1) {
              const record = dataSource[index]
              const num = record.number + 1
              if (num <= record.total) {
                Object.assign(record, { number: num })
                dataSource.splice(index, 1, record)
              }
            } else {
              const { store } = this
              GetProduct(code)
                .then(res => {
                  if (res.storeId == store.id) {
                    this.dataSource.push({
                      id: res.id,
                      code: res.code,
                      name: res.name,
                      type: res.type,
                      price: res.price,
                      total: res.number,
                      number: 1,
                      checked: true,
                      vitaminA: res.vitaminA,
                      vitaminB: res.vitaminB,
                      vitaminC: res.vitaminC
                    })
                  } else this.$toast(res.name + '不是本店商品')
                })
                .catch(err => {
                  this.$toast(err)
                })
            }
          } else this.$toast('二维码错误')
        }
      })
    },
    //点击提交订单
    onSubmit() {
      if (this.loading) return
      window.wx.scanQRCode({
        needResult: 1,
        scanType: ['qrCode'],
        success: qrres => {
          const [type, id, code, wallet] = qrres.resultStr.split(':')
          if (type == 'u') {
            const { totalPrice, store } = this
            if (wallet * 100 < totalPrice) this.$dialog.alert({ title: '提交失败', message: '用户余额不足' })
            else {
              this.loading = true
              const products = this.dataSource.filter(f => f.checked).map(m => ({ productId: m.id, number: m.number, price: m.price }))
              SubmitShopOrder({ userId: id, userCode: code, storeId: store.id, payMode: '余额扣款', discount: 0, products })
                .then(res => {
                  if (res) {
                    this.$toast('提交成功')
                    this.dataSource = []
                  }
                })
                .catch(err => {
                  this.$dialog.alert({ title: '提交失败', message: err })
                })
                .finally(() => {
                  this.loading = false
                })
            }
          } else this.$toast('二维码错误')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.hl-wrapper {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f7;
  .hl-content {
    box-sizing: border-box;
    flex: 1;
    position: relative;
    width: 100%;
    height: 100%;
    padding: 8px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  .hl-scan {
    position: fixed;
    bottom: 70px;
    right: 20px;
    height: 50px;
    width: 50px;
    border-radius: 50%;
    background-color: #1989fa;
    opacity: 0.8;
    color: white;
    font-size: 2em;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .hl-price {
    margin-right: 16px;
  }
  /deep/.van-submit-bar {
    position: static;
  }
  /deep/.van-checkbox {
    margin-right: 12px;
  }
  /deep/.van-cell__title {
    flex: 0 0 60%;
    .van-tag {
      margin-right: 4px;
    }
  }
  /deep/.van-cell__value {
    flex: 1 1 auto;
  }
}
</style>
